import axios from '@/utils/request'
const ORDER_STATUS = {
  '-2': '支付失败',
  '-1': '已取消',
  1: '待支付',
  2: '已支付',
  3: '已发货',
  4: '已结算',
  5: '已完成'
}
const STATUS_COLOR = {
  '-2': 'danger',
  '-1': 'info',
  1: 'primary',
  2: 'warning',
  3: 'warning',
  4: 'success',
  5: 'success'
}

export default {
  Order: {
    form: {
      fields: [
        'store',
        {
          property: 'status',
          type: 'select',
          type_options: {
            options: [
              { value: '-2', label: '支付失败' },
              { value: '-1', label: '已取消' },
              { value: '1', label: '待支付' },
              { value: '2', label: '已支付' },
              { value: '3', label: '已发货' },
              { value: '4', label: '已结算' },
              { value: '5', label: '已完成' }
            ]
          }
        },
        {
          property: 'staff',
          field_options: { label: '业务员' },
          required: false
        },
        {
          property: 'leader',
          field_options: { label: '小队长' },
          required: false
        },
        {
          property: 'broker',
          field_options: { label: '团队长' },
          required: false
        }
      ]
    },
    list: {
      export: {
        query: {
          '@display': `{
            'id' : 'entity.getId()',
            'createdTime' : 'entity.getCreatedTime().format("Y-m-d H:i:s")',
            'paidTime' : 'entity.getInvoice().getPaidTime().format("Y-m-d H:i:s")',
            'store' : 'entity.getStore().__toString()',
            'name': 'entity.getName()',
            'principal': 'entity.getPrincipal()',
            'staff' : 'entity.getStaff().__toString()',
            'squad' : 'entity.getSquad().__toString()',
            'leader' : 'entity.getLeader().__toString()',
            'broker' : 'entity.getBroker().__toString()',
            'items' : 'ArrayCommon.reduce(entity.getItems().toArray(), "carry~item.__toString()~hyphen", null, { hyphen : "; "} )',
            'status' : '${JSON.stringify(ORDER_STATUS)}[entity.getStatus()]',
            'totalPrice' : 'entity.getTotalPrice()',
            'price' : 'entity.getPrice()',
            'payType' : 'entity.getInvoice().getPayment() == "balance" ? "余额支付" : "扫码支付"',
            'comment': 'entity.getComment()'
          }`,
          limit: 10000000
        },
        label: {
          'id': 'id',
          'createdTime': '创建时间',
          'paidTime': '支付时间',
          'store': '店铺',
          'name': '客户',
          'principal': '负责人',
          'staff': '业务',
          'squad': '小队',
          'leader': '队长',
          'broker': '经纪人',
          'items': '产品',
          'status': '状态',
          'totalPrice': '总价',
          'price': '实收',
          'payType': '支付方式',
          'comment': '备注'
        }
      },
      disabled_actions: ['new', 'delete', 'export'],
      actions: [
        {
          name: 'refund',
          position: 'list',
          component: {
            props: ['record', 'refresh'],
            data() {
              return {
                loading: false,
                show: false,
                items: []
              }
            },
            created() {
              this.axios.get(`/manage/order-items`, {
                params: {
                  '@filter': `entity.getOrder().getId() == ${this.record.id}`,
                  '@expands': `['entity.shippings']`
                }
              }).then((res) => {
                for (let i of res.data) {
                  i['shippingQuantity'] = i.quantity
                  // 查是否有发货记录，有的话，还需要进行扣减
                  let shippingedQuantity = 0
                  if (i.shippings && i.shippings.length > 0) {
                    for (let s of i.shippings) {
                      shippingedQuantity += s.__metadata.quantity
                    }
                  }
                  i['shippingQuantity'] = parseInt(i.quantity) - shippingedQuantity
                  i['shippingedQuantity'] = shippingedQuantity
                }
                this.items = res.data
              })
            },
            render(h) {
              if (parseInt(this.record.status) === 2) {
                return (
                  <span>
                    <el-popconfirm title='确定退款当前订单？'
                      {...{
                        on: {
                          onConfirm: (val) => {
                            this.loading = true
                            axios.post(`/manage/orders/${this.record.id}/cancel-and-refund`).then((res) => {
                              this.$message.success('执行成功！')
                              this.refresh()
                            }).finally(() => {
                              this.loading = false
                            })
                          }
                        }
                      }}>
                      <el-button slot='reference' size='small' type='danger' icon='el-icon-bank-card' loading={this.loading} plain>退款</el-button>
                    </el-popconfirm>
                    <el-dialog
                      title='发货操作'
                      visible={this.show}
                      width='60%'>
                      <div >
                        <el-row>
                          <el-col span={8}><div>产品</div></el-col>
                          <el-col span={4}><div>采购数量</div></el-col>
                          <el-col span={4}><div>已发</div></el-col>
                          <el-col span={4}>
                            <div>
                              发货数量
                            </div>
                          </el-col>
                        </el-row>
                        <el-divider></el-divider>
                        {this.items.map((item, index) => (
                          <div>
                            <el-row>
                              <el-col span={8}><div>{item.specificationTitle}</div></el-col>
                              <el-col span={4}><div>{item.quantity}</div></el-col>
                              <el-col span={4}><div>{item.shippingedQuantity}</div></el-col>
                              <el-col span={4}>
                                <div>
                                  <el-input-number v-model={item.shippingQuantity} min={0} max={item.quantity - item.shippingedQuantity} ></el-input-number>
                                </div>
                              </el-col>
                            </el-row>
                            <el-divider></el-divider>
                          </div>
                        ))}
                      </div>
                      <div style='text-align:right'>
                        <el-button onClick={() => { this.show = false }}>取消</el-button>
                        <el-button type='primary' onClick={() => {
                          console.log(this.items)
                          const shippingData = []
                          for (let i of this.items) {
                            if (i.shippingQuantity > 0) {
                              shippingData.push({
                                orderItem: i.id,
                                quantity: i.shippingQuantity
                              })
                            }
                          }
                          if (shippingData.length > 0) {
                            this.axios.post(`/manage/order-shippings/batch-update`, shippingData).then((res) => {
                              this.$message.success('发货成功！')
                              this.show = false
                            })
                          } else {
                            this.$message.error('没有发货内容！')
                          }
                        }}>确 定 发 货</el-button>
                      </div>
                    </el-dialog>
                    <el-button slot='reference' size='small' onClick={() => { this.show = true }} type='primary' icon='el-icon-truck' loading={this.loading} plain>发货</el-button>
                  </span>
                )
              } else if (this.record.status >= 5) {
                return (
                  <el-popconfirm title='确定回滚当前订单的所有分账金额？'
                    {...{
                      on: {
                        onConfirm: (val) => {
                          this.loading = true
                          axios.post(`/manage/orders/${this.record.id}/settle-reverse`).then((res) => {
                            axios.post(`/manage/orders/${this.record.id}/settle-remove`).then((res) => {
                              this.$message.success('执行成功！')
                              this.refresh()
                            })
                          }).finally(() => {
                            this.loading = false
                          })
                        }
                      }
                    }}>
                    <el-button slot='reference' size='small' type='danger' icon='el-icon-refresh-left' loading={this.loading} plain>回滚分账</el-button>
                  </el-popconfirm>
                )
              } else if (parseInt(this.record.status) === 3) {
                return (
                  <span>
                    <el-popconfirm title='确定退款当前订单？'
                      {...{
                        on: {
                          onConfirm: (val) => {
                            this.loading = true
                            axios.post(`/manage/orders/${this.record.id}/cancel-and-refund`).then((res) => {
                              this.$message.success('执行成功！')
                              this.refresh()
                            }).catch((err) => {
                              console.log('err', err)
                              this.loading = false
                            })
                          }
                        }
                      }}>
                      <el-button slot='reference' size='small' type='danger' icon='el-icon-bank-card' loading={this.loading} plain>退款</el-button>
                    </el-popconfirm>
                    <el-popconfirm title='确定结算当前订单？'
                      {...{
                        on: {
                          onConfirm: (val) => {
                            this.loading = true
                            axios.post(`/store/${this.record.store.id}/orders/${this.record.id}/settle-generate`).then((res) => {
                              this.$message.success('执行成功！')
                              this.refresh()
                            }).finally(() => {
                              this.loading = false
                            })
                          }
                        }
                      }} style={{ marginLeft: '3px' }}>
                      <el-button slot='reference' size='small' type='success' icon='el-icon-delete' loading={this.loading} plain>结算</el-button>
                    </el-popconfirm>
                  </span>
                )
              } else if (parseInt(this.record.status) === 4) {
                return (
                  <div>
                    <el-popconfirm title='确定反结算当前订单？'
                      {...{
                        on: {
                          onConfirm: (val) => {
                            this.loading = true
                            axios.post(`/store/${this.record.store.id}/orders/${this.record.id}/settle-remove`).then((res) => {
                              this.$message.success('执行成功！')
                              this.refresh()
                            }).finally(() => {
                              this.loading = false
                            })
                          }
                        }
                      }} style={{ marginLeft: '3px' }}>
                      <el-button slot='reference' size='small' type='warning' icon='el-icon-delete' loading={this.loading} plain>反结算</el-button>
                    </el-popconfirm>
                    <el-popconfirm title='确定对当前订单执行分账？'
                      {...{
                        on: {
                          onConfirm: (val) => {
                            this.loading = true
                            axios.post(`/store/${this.record.store.id}/orders/${this.record.id}/settle-execute`).then((res) => {
                              this.$message.success('执行成功！')
                              this.refresh()
                            }).finally(() => {
                              this.loading = false
                            })
                          }
                        }
                      }} style={{ marginLeft: '3px' }}>
                      <el-button slot='reference' size='small' type='primary' icon='el-icon-delete' loading={this.loading} plain>执行分账</el-button>
                    </el-popconfirm>
                  </div>
                )
              }
            }
          }
        }
        // {
        //   name: 'button',
        //   position: 'list',
        //   component: {
        //     props: ['record', 'refresh'],
        //     data() {
        //       return {
        //         loading: false
        //       }
        //     },
        //     render(h) {
        //       if (parseInt(this.record.status) === 4) {
        //         return (
        //           <div>
        //             <el-popconfirm title='确定反结算当前订单？'
        //               {...{
        //                 on: {
        //                   onConfirm: (val) => {
        //                     this.loading = true
        //                     axios.post(`/store/${this.record.store.id}/orders/${this.record.id}/settle-remove`).then((res) => {
        //                       this.$message.success('执行成功！')
        //                       this.refresh()
        //                     }).finally(() => {
        //                       this.loading = false
        //                     })
        //                   }
        //                 }
        //               }} style={{ marginLeft: '3px' }}>
        //               <el-button slot='reference' size='small' type='warning' icon='el-icon-delete' loading={this.loading} plain>反结算</el-button>
        //             </el-popconfirm>
        //             <el-popconfirm title='确定对当前订单执行分账？'
        //               {...{
        //                 on: {
        //                   onConfirm: (val) => {
        //                     this.loading = true
        //                     axios.post(`/store/${this.record.store.id}/orders/${this.record.id}/settle-execute`).then((res) => {
        //                       this.$message.success('执行成功！')
        //                       this.refresh()
        //                     }).finally(() => {
        //                       this.loading = false
        //                     })
        //                   }
        //                 }
        //               }} style={{ marginLeft: '3px' }}>
        //               <el-button slot='reference' size='small' type='primary' icon='el-icon-delete' loading={this.loading} plain>执行分账</el-button>
        //             </el-popconfirm>
        //           </div>
        //         )
        //       } else if (this.record.laterPay === false && parseInt(this.record.status) === 3) {
        //         return (
        //           <el-popconfirm title='确定结算当前订单？'
        //             {...{
        //               on: {
        //                 onConfirm: (val) => {
        //                   this.loading = true
        //                   axios.post(`/store/${this.record.store.id}/orders/${this.record.id}/settle-generate`).then((res) => {
        //                     this.$message.success('执行成功！')
        //                     this.refresh()
        //                   }).finally(() => {
        //                     this.loading = false
        //                   })
        //                 }
        //               }
        //             }} style={{ marginLeft: '3px' }}>
        //             <el-button slot='reference' size='small' type='success' icon='el-icon-delete' loading={this.loading} plain>结算</el-button>
        //           </el-popconfirm>
        //         )
        //       }
        //     }
        //   }
        // }
      ],
      query: {
        '@filter': `entity.getStatus() != 0`,
        '@order': 'entity.id|DESC',
        '@expands': "['entity.invoice']"
      },
      list_display: [
        'id',
        // 'invoice',
        // 'user',
        'createdTime',
        'store',
        {
          property: 'staff',
          label: '业务'
        },
        {
          property: 'name',
          label: '客户'
        },
        {
          property: 'principal',
          label: '负责人'
        },
        {
          property: 'squad',
          label: '所属小队'
        },
        { property: 'leader', label: '小队长' },
        { property: 'broker', label: '辅导员' },
        'items',
        {
          property: 'status',
          label: '订单状态',
          component: {
            props: ['data', 'record'],
            data() {
              return {
                status: ORDER_STATUS,
                color: STATUS_COLOR,
                show: false,
                settleItems: []
              }
            },
            render(h) {
              return <div>
                <el-tag onClick={() => {
                  console.log(this.record)
                  if (parseInt(this.data) === 2) {
                    this.$message('未有结算信息！')
                  } else {
                    this.axios.get(`/manage/settle-items`, {
                      params: {
                        '@filter': `entity.getSettle().getOrderItem().getOrder().getId() == ${this.record.id}`
                      }
                    }).then((res) => {
                      console.log(res.data)
                      this.settleItems = res.data
                      this.show = true
                    })
                  }
                }} type={this.color[this.data]} effect='plain'>{this.status[this.data]}</el-tag>

                <el-dialog
                  title='结算明细'
                  visible={this.show}
                  width='50%'
                  onClose={() => { this.show = false }}
                >
                  <el-table
                    data={this.settleItems}
                    style='width: 100%'>
                    <el-table-column
                      prop='user.__toString'
                      label='账号'>
                    </el-table-column>
                    <el-table-column
                      prop='staff.__toString'
                      label='员工'>
                    </el-table-column>
                    <el-table-column
                      prop='amount'
                      label='金额'>
                    </el-table-column>
                    {/* <el-table-column
                      prop='settled'
                      label='是否已到账'>
                    </el-table-column> */}
                  </el-table>
                  <span slot='footer' class='dialog-footer'>
                    <el-button type='primary' onClick={() => { this.show = false }}>关 闭</el-button>
                  </span>
                </el-dialog>
              </div>
            }
          }
        },
        'price',
        {
          property: 'invoice',
          label: '支付方式',
          component: {
            props: ['record'],
            render(h) {
              console.log('invoice',this.record)
              if (this.record.invoice.__metadata.status === 1) {
                if (this.record.invoice.__metadata.payment === 'balance') {
                  return <div>余额支付</div>
                } else {
                  return <div>扫码支付</div>
                }
              }
              if (this.record.invoice.__metadata.status === 0) {
                return <div>未支付</div>
              }
            }
          }
        },
        'comment'
      ]
    }
  }
}
